<script setup>
import {
  getwaterwayBridgeDistribution,
  getAccidentBaseInfo,
} from "../utils/apis";
import { ref, onMounted, watch, defineEmits, nextTick } from "vue";
import { useRouter } from "vue-router";
import Bridge from "./bridge.vue";
import Choose from "./choose.vue";
import { gcj02towgs84 } from "../common/js/geoParser";
const router = useRouter();
const isShowAcc = ref(false);
const goToAccDetail = () => {
  // 跳转到事故详情
  router.push({
    path: "/accidentInformation",
    query: { id: accId.value, lat: lat.value, lon: lon.value },
  });
};
const emit = defineEmits(["closeChooseBtn"]);
// 桥梁信息
const showBridge = ref(false);
const isUpdate = ref(true);
const closeBridgeBtn = () => {
  // 关闭弹窗清空id
  isUpdate.value = false;
  bridgeId.value = "";
  showBridge.value = false;
};
// 桥梁信息
const showBridgeBox = (val) => {
  if (val.bridgeId != "" || val.bridgeId != undefined || val.bridgeId != null) {
    isUpdate.value = true;
    bridgeId.value = val.bridgeId;
    setTimeout(() => {
      showBridge.value = true;
    }, 100);
  }
};

// 发生事故的桥梁位置
const positionAcc = ref([]);
// 事故id
const accId = ref("");
// 事故经纬度
const lat = ref("");
const lon = ref("");
const data = ref({
  code: "440000",
});

// 筛选
const showChooseBox = ref(false);
const showChooseBoxFn = () => {
  showChooseBox.value = true;
};
const closeChooseBtn = (value) => {
  showChooseBox.value = false;
};
// 地图选项
const showWhichMap = ref(false);
const showChangeMap = () => {
  showWhichMap.value = true;
};

let bridgeId = ref("");
let bridgeName = ref("");
// 默认展示广东省的桥梁坐标点
const getChooseBridgeList = ref([]);
//事故点
const getAccBridgeList = ref([]);
// 地图坐标
let projection = ol.proj.get("EPSG:4326");
// 基础地图服务切片地址
let tileUrl =
  "http://19.15.16.143:6080/arcgis/rest/services/waterWayMap/gdhd22_tile/MapServer/tile/{z}/{y}/{x}";
// 坐标原点
let origin = [-400.0, 399.9999999999998];

// 分辨率
let resolutions = [
  0.010998658750001491, 0.005499329375000746, 0.002749664687500373,
  0.0013772106150255138, 6.875571549396887e-4, 3.437060039091665e-4,
  1.7185181222408033e-4, 8.592471638153725e-5, 4.296116846026571e-5,
  2.147939449962994e-5, 1.0738507519312054e-5, 5.368064029153112e-6,
  2.684032014576556e-6, 1.342016007288278e-6,
];
//地图范围
let fullExtent = [-180, -90, 180, 90];
let tileGrid = new ol.tilegrid.TileGrid({
  tileSize: 256,
  origin: origin,
  extent: fullExtent,
  resolutions: resolutions,
});
// 瓦片数据源
let tileArcGISXYZ = new ol.source.XYZ({
  tileGrid: tileGrid,
  projection: projection,
  url: tileUrl,
});
//请求高德图层
let AMapLayer = new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
  }),
  visible: true,
});
// 瓦片图层
let ArcMapLayer = new ol.layer.Tile({
  source: tileArcGISXYZ,
  visible: false,
});

//实例化ZoomToExtent
let zoomToExtent = new ol.control.ZoomToExtent({
  extent: [
    //Todo 这个范围应该怎么确定
    13100000, 4290000, 13200000, 5210000,
  ],
})
const updatePoint = (val) => {
  layer
    .getSource()
    .getFeatures()
    .forEach(function (feature) {
      layer.getSource().removeFeature(feature);
    });
  layerAcc
    .getSource()
    .getFeatures()
    .forEach(function (feature) {
      layerAcc.getSource().removeFeature(feature);
    });
  positionList.value = [];
  positionAcc.value = [];

  getChooseBridgeList.value.map((el) => {
    if (
      (el.latitude != "" && el.latitude != undefined && el.latitude != null) ||
      (el.longitude != "" && el.longitude != undefined && el.longitude != null)
    ) {
      let positionItem;
      if(val==1){
         positionItem = {
            position: [el.longitude, el.latitude],
            bridgeid: el.bridgeid,
            bridgeName: el.bridgeName,
          };
      }else{
        positionItem = {
            position: gcj02towgs84(Number(el.longitude), Number(el.latitude)),
            bridgeid: el.bridgeid,
            bridgeName: el.bridgeName,
          };
      }
      positionList.value.push(positionItem);
    }
  });
  let datalist = [];
  positionList.value.forEach((el) => {
    let anchor = new ol.Feature({
      geometry: new ol.geom.Point(el.position),
    });
    anchor.setProperties({
      bridgeName: el.bridgeName,
      bridgeId: el.bridgeid,
    });
    anchor.setStyle(
      new ol.style.Style({
        image: new ol.style.Icon({
          src: new URL("../static/images/bridge.png", import.meta.url).href,
        }),
      })
    );
    datalist.push(anchor);
  });
  layer.getSource().addFeatures(datalist); //添加点

  getAccBridgeList.value.map((el) => {
    if (
      (el.latitude != "" && el.latitude != undefined && el.latitude != null) ||
      (el.longitude != "" && el.longitude != undefined && el.longitude != null)
    ) {
      let positionItem;
      // 如果是航道图,坐标需要转化
      if (ArcMapLayer.N.visible) {
        positionItem = {
          position: gcj02towgs84(Number(el.longitude), Number(el.latitude)),
           id: el.id,
          bridgeName: el.bridgeName,
        };
      } else {
        positionItem = {
          position: [el.longitude, el.latitude],
          id: el.id,
          bridgeName: el.bridgeName,
        };
      }
      positionAcc.value.push(positionItem);
    }
  });
  positionAcc.value.forEach((el) => {
    let accanchor = new ol.Feature({
      geometry: new ol.geom.Point(el.position),
    });
    accanchor.setProperties({
      bridgeName: el.bridgeName,
      accId: el.id,
    });
    accanchor.setStyle(
      new ol.style.Style({
        image: new ol.style.Icon({
          src: new URL(
            "../static/images/accidentInformation.png",
            import.meta.url
          ).href,
        }),
      })
    );
    // 添加到之前的创建的layer中去
    layerAcc.getSource().addFeature(accanchor);
  });
};
// 显示高德地图
const getGeoMap = () => {
  AMapLayer.setVisible(true);
  ArcMapLayer.setVisible(false);
  showWhichMap.value = false;
  updatePoint(1);
};
// 显示航道地图
const getArcgisMap = () => {
  ArcMapLayer.setVisible(true);
  AMapLayer.setVisible(false);
  showWhichMap.value = false;
  updatePoint(2);
};
const positionList = ref([]); //高德
const getChooseDataList = (data) => {
  showChooseBox.value = false;
  nextTick(() => {
    initMap(data);
  });
};
// 我们需要一个vector的layer来放置图标
let mark = new ol.source.Vector();
let layer = new ol.layer.Vector({
  source: mark,
});
let layerAcc = new ol.layer.Vector({
  source: new ol.source.Vector(),
});
function initMap(data) {
  let map = new ol.Map({
    target: "map",
    layers: [ArcMapLayer, AMapLayer],
    view: new ol.View({
      //初始化中心点坐标
      center: [113.359194, 22.745479],
      resolutions: resolutions,
      // 注意：此处指定缩放级别不能通过zoom来指定，指定了也无效，必须通过resolution来指定
      resolution: 8.423434728299542e-4,
      projection: projection,
      extent: [
        108.99467974897915, 20.44175014466765, 116.47213595980087,
        23.48746023213043,
      ],
    }),
  });
  let selectSingleClick = new ol.interaction.Select();
  map.addInteraction(selectSingleClick);
  selectSingleClick.on("select", function (e) {
    bridgeId.value = "";
    let features = e.target.getFeatures().getArray();
    if (features.length > 0) {
      // 事故的
      if (features[0].N.accId) {
        accId.value = features[0].N.accId;
        bridgeName.value = features[0].N.bridgeName;
        isShowAcc.value = true;
      } else {
        // 桥梁的
        bridgeId.value = features[0].N.bridgeId;
        showBridge.value = true;
        isUpdate.value = true;
      }
    }
  });
  getwaterwayBridgeDistribution({ data }).then((res) => {
    positionList.value = [];
    layer
      .getSource()
      .getFeatures()
      .forEach(function (feature) {
        layer.getSource().removeFeature(feature);
      });
    if (res.code == 200) {
      getChooseBridgeList.value = res.data;
      getChooseBridgeList.value.map((el) => {
        if (
          (el.latitude != "" &&
            el.latitude != undefined &&
            el.latitude != null) ||
          (el.longitude != "" &&
            el.longitude != undefined &&
            el.longitude != null)
        ) {
          let positionItem;
          // 如果是航道图,坐标需要转化
          if (ArcMapLayer.N.visible) {
            positionItem = {
              position: gcj02towgs84(Number(el.longitude), Number(el.latitude)),
              bridgeid: el.bridgeid,
              bridgeName: el.bridgeName,
            };
          } else {
            positionItem = {
              position: [el.longitude, el.latitude],
              bridgeid: el.bridgeid,
              bridgeName: el.bridgeName,
            };
          }
          positionList.value.push(positionItem);
        }
      });
      let datalist = [];
      positionList.value.forEach((el) => {
        let anchor = new ol.Feature({
          geometry: new ol.geom.Point(el.position),
        });
        anchor.setProperties({
          bridgeName: el.bridgeName,
          bridgeId: el.bridgeid,
        });
        anchor.setStyle(
          new ol.style.Style({
            image: new ol.style.Icon({
              src: new URL("../static/images/bridge.png", import.meta.url).href,
            }),
          })
        );
        datalist.push(anchor);
      });
      layer.getSource().addFeatures(datalist); //添加点
    }
  });
  getAccidentBaseInfo().then((res) => {
    positionAcc.value = [];
    layer
      .getSource()
      .getFeatures()
      .forEach(function (feature) {
        layer.getSource().removeFeature(feature);
      });
    if (res.code == 200) {
      getAccBridgeList.value = res.data;
      getAccBridgeList.value.map((el) => {
        if (
          (el.latitude != "" &&
            el.latitude != undefined &&
            el.latitude != null) ||
          (el.longitude != "" &&
            el.longitude != undefined &&
            el.longitude != null)
        ) {
          let positionItem;
          // 如果是航道图,坐标需要转化
          if (ArcMapLayer.N.visible) {
            positionItem = {
              position: gcj02towgs84(Number(el.longitude), Number(el.latitude)),
              id: el.id,
              bridgeName: el.bridgeName,
            };
          } else {
            positionItem = {
              position: [el.longitude, el.latitude],
              id: el.id,
              bridgeName: el.bridgeName,
            };
          }
          positionAcc.value.push(positionItem);
        }
      });
      positionAcc.value.forEach((el) => {
        let accanchor = new ol.Feature({
          geometry: new ol.geom.Point(el.position),
        });
        accanchor.setProperties({
          bridgeName: el.bridgeName,
          accId: el.id,
        });
        accanchor.setStyle(
          new ol.style.Style({
            image: new ol.style.Icon({
              src: new URL(
                "../static/images/accidentInformation.png",
                import.meta.url
              ).href,
            }),
          })
        );
        // 添加到之前的创建的layer中去
        layerAcc.getSource().addFeature(accanchor);
      });
    }
  });
  map.addLayer(layer);
  map.addLayer(layerAcc);
}
watch(
  bridgeId,
  (newVal, oldVal) => {
    console.log(newVal);
  },
  {
    deep: true,
    immediate: true,
  }
);
watch(showChooseBox, (newVal, oldVal) => {}, {
  deep: true,
  immediate: true,
});
defineExpose({ showChangeMap, showChooseBoxFn });
onMounted(() => {
  setTimeout(() => {
    initMap(data);
  }, 100);
});
</script>
<template>
  <div class="main">
    <div id="map"></div>
    <div id="geoMap"></div>
    <van-popup v-model:show="isShowAcc" closeable>
      <div class="accBox">
        <div class="title">
          <span>提示</span>
        </div>
        <div class="content">{{ bridgeName }}发生船碰桥事故,请您立即处理</div>
        <div class="btn" @click="goToAccDetail">查看详情</div>
      </div>
    </van-popup>
    <!-- 桥梁信息 -->
    <van-popup
      v-model:show="showBridge"
      round
      position="bottom"
      :lazy-render="true"
      :style="{ height: '35%', overflow: 'hidden' }"
      @click-close-icon="closeBridgeBtn"
      :overlay="true"
      :closeable="true"
      :overlay-style="{ background: 'rgba(255,255,255,0)' }"
    >
      <Bridge :bridgeId="bridgeId" v-if="isUpdate"></Bridge>
    </van-popup>
    <!-- 筛选 -->
    <van-popup
      v-model:show="showChooseBox"
      round
      position="bottom"
      :style="{ height: '60%' }"
      @click-close-icon="closeChooseBtn"
      :overlay="true"
      :closeable="true"
      :overlay-style="{ background: 'rgba(255,255,255,0)' }"
      :z-index="1000"
    >
      <Choose
        @closeChooseBtn="closeChooseBtn"
        @getChooseDataList="getChooseDataList"
      ></Choose>
    </van-popup>
    <!-- 地图弹窗 -->
    <van-popup v-model:show="showWhichMap" closeable>
      <div class="MapBox">
        <div class="title">
          <span>选取地图</span>
        </div>
        <div class="contentBox">
          <div class="content" style="margin-right: 16px" @click="getGeoMap">
            <img src="../static/images/geoMap.png" alt="" />
          </div>
          <div class="content" @click="getArcgisMap">
            <img src="../static/images/channelMap.png" alt="" />
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.main {
  position: relative;
  #map {
    width: 375px;
    height: 100%;
  }
  #geoMap {
    width: 375px;
    height: 100%;
  }
  .accBox {
    padding: 5px 20px;
    background: #ffffff;
    box-shadow: 2px 4px 16px 2px rgba(47, 114, 191, 0.35);
    border-radius: 4px 4px 4px 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .title {
      margin-top: 16px;
      margin-bottom: 8px;
      font-size: 20px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.9);
      display: flex;
      flex-direction: row;
    }
    .content {
      font-size: 16px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.9);
    }
    .btn {
      margin-bottom: 16px;
      margin-top: 33px;
      width: 105px;
      height: 40px;
      background: #266fe8;
      border-radius: 4px 4px 4px 4px;
      text-align: center;
      line-height: 40px;
      font-size: 16px;
      font-weight: 500;
      color: #ffffff;
    }
  }
  .MapBox {
    width: 321px;
    height: 200px;
    background: #ffffff;
    box-shadow: 2px 4px 16px 2px rgba(47, 114, 191, 0.35);
    border-radius: 4px 4px 4px 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 2px;
    .title {
      margin-top: 16px;
      margin-bottom: 30px;
      font-size: 20px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.9);
      display: flex;
      flex-direction: row;
    }
    .contentBox {
      display: flex;
      .content {
        width: 136px;
        height: 100px;
        border-radius: 2px 2px 2px 2px;
        opacity: 1;
        border: 1px solid #266fe8;
        position: relative;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .content:first-of-type::after {
        content: "高德地图";
      }
      .content:last-of-type::after {
        content: "航道地图";
      }
      .content:first-of-type::after,
      .content:last-of-type::after {
        position: absolute;
        bottom: -1px;
        left: 0;
        background: rgba(0, 0, 0, 0.5);
        color: #ffffff;
        width: 100%;
        height: 28px;
        line-height: 28px;
        text-indent: 10px;
      }
    }
  }
}
</style>